package com.yubest.seataorder.service;

import com.yubest.seataorder.feign.AccountServiceFeign;
import com.yubest.seataorder.feign.StockServiceFeign;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.MessageFormat;

@Service
@Slf4j
public class OrderService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private AccountServiceFeign accountServiceFeign;

    @Autowired
    private StockServiceFeign stockServiceFeign;

    @GlobalTransactional
    public boolean create() {
        int skuId = 1;
        int stock = 1;
        int accountId = 1;
        BigDecimal money = new BigDecimal("10");
        //下单
        this.createOrder(skuId, accountId, money);
        //扣钱
        if (!accountServiceFeign.sub(accountId, money)) {
            log.error("扣钱失败");
            throw new RuntimeException();
        }
        //扣库存
        if (!stockServiceFeign.sub(skuId, stock)) {
            log.error("扣库存失败");
            throw new RuntimeException();
        }
        return true;
    }

    private void createOrder(Integer skuId, Integer accountId, BigDecimal money) {
        jdbcTemplate.execute(MessageFormat.format("INSERT INTO `t_order_info`(`sku_id`, `account_id`, `money`) VALUES ({0}, {1}, {2})", skuId, accountId, money));
    }
}
